<?php namespace App\Controllers;

use CodeIgniter\Controller;

class Main extends Controller{







    public function __construct(){
        date_default_timezone_set('Asia/Shanghai');
        $this->db  = \Config\Database::connect();
        $this->data = array();

        $this->data['catagory_all'] = $this->db->table('catagory')->orderBy('catagory_date', 'DESC')->get()->getResultArray();
        $this->data['catagory_sidebar'] = $this->catagory_sidebar();
    }


	public function index(){

        
        //获得左侧、顶部的名称
        $this->data['catagory_title'] = '';
        $this->data['catagory_id'] = '';

        //获得数组
        $posts_array = $this->db->table('posts')->orderBy('posts_ctime', 'DESC')->limit(10)->get()->getResultArray();
        $this->data['posts'] = $this->tool_post_array_specific($posts_array);


        $this->viewer('index');
    }



















// =========================================
// Catagory
// =========================================

    public function catagory_sidebar(){

        $catagory_sidebar = array();

        $catagory_sidebar['0'] = $this->db->table('catagory')->where('catagory_status', '0')->orderBy('catagory_date', 'DESC')->get()->getResultArray();
        $catagory_sidebar['1'] = $this->db->table('catagory')->where('catagory_status', '1')->orderBy('catagory_date', 'DESC')->get()->getResultArray();
        $catagory_sidebar['2'] = $this->db->table('catagory')->where('catagory_status', '2')->orderBy('catagory_date', 'DESC')->get()->getResultArray();
        $catagory_sidebar['3'] = $this->db->table('catagory')->where('catagory_status', '3')->orderBy('catagory_date', 'DESC')->get()->getResultArray();

        return $catagory_sidebar;
    }









    public function catagory($id){

        //获得对应catagory_id下的post数据
        $posts_array = $this->db->table('posts')->where('posts_catagory', $id)->orderBy('posts_ctime', 'DESC')->get()->getResultArray();

        //将sql数组具体化
        $this->data['posts'] = $this->tool_post_array_specific($posts_array);

        //获得左侧、顶部的名称
        $result_catagory = $this->db->table('catagory')->where('catagory_id', $id)->get()->getResultArray();
        $this->data['catagory'] = $result_catagory[0];

        $this->viewer('main');
    }




    public function catagory_insect(){
        $data = array(
            'catagory_date'  => date('Y-m-d'),
            'catagory_title' => $_POST["catagory_title"],
            'catagory_status' => '1',
        );

        $this->db->table('catagory')->insert($data);

        $new_catagory_id = $this->db->insertID();

        $url = base_url('main/catagory/' . $new_catagory_id);

        $this->response->redirect($url);
    }


    public function catagory_edit($id){
        $result_catagory = $this->db->table('catagory')->where('catagory_id', $id)->get()->getResultArray();
        $this->data['catagory'] = $result_catagory[0];

        $this->viewer('catagory_edit');
    }


    public function catagory_update(){
        $data = array(
            'catagory_date'   =>  $_POST["catagory_date"],
            'catagory_title'  =>  $_POST["catagory_title"],
            'catagory_status' =>  $_POST["catagory_status"],
            'catagory_task'   =>  $_POST["catagory_task"],
            'catagory_note'   =>  $_POST["catagory_note"],
        );

        $this->db->table('catagory')->where('catagory_id', $_POST['catagory_id'])->update($data);

        $url = base_url('main/catagory/' . $_POST['catagory_id']);
        $this->response->redirect($url);
    }














// =========================================
// Tag
// =========================================

    public function tag($id){


        //获得数据
        // $posts_array = $this->db->table('posts')->where('posts_catagory', $id)->orderBy('posts_ctime', 'DESC')->get()->getResultArray();
        $post_has_tagid_array = $this->db->query("SELECT * FROM `posts` WHERE FIND_IN_SET($id,`posts_tag`)")->getResultArray();

        //将sql数组具体化
        $this->data['posts'] = $this->tool_post_array_specific($post_has_tagid_array);

        //获得顶部的名称
        $temp = $this->tool_tag_title($id);
        $this->data['tag_title'] = $temp[0]['tag_title'];

        //获得左侧的列表
        $this->data["tag_group_array"] = $this->tag_get_all();

        $this->viewer('tag');
    }





    public function tags(){

        $this->data["tag_group_array"] = $this->tag_get_all();

        $this->viewer('tags');
    }



    public function tag_get_all(){

        $tag_get_all = array();

        $tag_get_all["1"] = $this->db->table('tag')->where('tag_group', '1')->orderBy('tag_order', 'ASC')->get()->getResultArray();
        $tag_get_all["2"] = $this->db->table('tag')->where('tag_group', '2')->orderBy('tag_order', 'ASC')->get()->getResultArray();
        $tag_get_all["3"] = $this->db->table('tag')->where('tag_group', '3')->orderBy('tag_order', 'ASC')->get()->getResultArray();
        $tag_get_all["4"] = $this->db->table('tag')->where('tag_group', '4')->orderBy('tag_order', 'ASC')->get()->getResultArray();
        $tag_get_all["5"] = $this->db->table('tag')->where('tag_group', '5')->orderBy('tag_order', 'ASC')->get()->getResultArray();
        $tag_get_all["6"] = $this->db->table('tag')->where('tag_group', '6')->orderBy('tag_order', 'ASC')->get()->getResultArray();

        return $tag_get_all;

    }



    public function tag_edit($tag_id){

       $result = $this->db->table('tag')->where('tag_id', $tag_id)->get()->getResultArray();
       $this->data["tag_info"] = $result[0];

        $this->viewer('tag_edit');

    }




    public function tag_insect(){

        $data = array(
            'tag_title' => $_POST["tag_title"],
            'tag_group' => $_POST["tag_group"],
            'tag_order' => $_POST["tag_order"]
        );


        $this->db->table('tag')->insert($data);

        $url = base_url('main/tags/');
        // var_dump($url);
        $this->response->redirect($url);
    }




    public function tag_update(){
        $data = array(
            'tag_title'   =>  $_POST["tag_title"],
            'tag_group'  =>  $_POST["tag_group"],
            'tag_order' =>  $_POST["tag_order"],
        );

        $this->db->table('tag')->where('tag_id', $_POST["tag_id"])->update($data);

        $url = base_url('main/tags/');
        $this->response->redirect($url);
    }




    public function tag_add($group_id){

        $this->data["tag_group"] = $group_id;

        $this->viewer('tag_add');

    }




    



























// =========================================
// Post
// =========================================


    public function insect_post(){
        $data = array(
            'posts_catagory' => $_POST["post_catagory_id"],
            'posts_tag'  => '',
            'posts_content'  => $_POST["post_content"],
            'posts_ctime'  => $_POST["post_ctime"],
        );

        $this->db->table('posts')->insert($data);

        $url = base_url('main/catagory/' . $_POST["post_catagory_id"] . '/' . $_POST["post_catagory_id"]);
        // var_dump($url);
        $this->response->redirect($url);

    }
    


    public function post($posts_catagory,$posts_id){

        $this->data["tag_group_array"] = $this->tag_get_all();

        $post_array = $this->db->table('posts')->where('posts_id', $posts_id)->get()->getResultArray();

        $post_specific = $this->tool_post_array_specific($post_array);
        $this->data['post'] = $post_specific[0];

        $this->data['catagory_title'] = $this->tool_catagory_title($posts_catagory);

        $this->viewer('post');
    }



    public function post_update(){


        // var_dump($_POST);

        
        if(isset($_POST['posts_tag'])){
            $posts_tag = implode(",",$_POST['posts_tag']);
        }else{
            $posts_tag = '';
        }


        $data = array(
            'posts_content' => $_POST['posts_content'],
            'posts_ctime' => $_POST['posts_ctime'],
            'posts_tag' => $posts_tag,
        );

        $this->db->table('posts')->where('posts_id', $_POST['posts_id'])->update($data);



        //上传文件
        // var_dump($this->request->getFiles());

        if($files = $this->request->getFiles())
        {
           foreach($files['posts_file'] as $file)
           {
            //   if ( ! $file->hasMoved())
              if ($file->isValid() && ! $file->hasMoved())
              {
                $newName = $file->getRandomName();
                $file->move('uploads/' . $_POST['posts_catagory'], $newName);
                //就算没有这个文件夹，它都会自动创建文件夹

                $new_name = $file->getName();
                //1548171014_38866f66308887eee50f.jpg
                $old_name = $file->getClientName();
                //the_picture.jpg
                $ext = substr(strrchr($new_name, '.'), 1);
                // $ext = $file->getExtension();
                // $ext = $file->getClientExtension();
                //jpg
                $size = $file->getSize('mb');
                //0.561
                //Working with Files
                //https://codeigniter4.github.io/CodeIgniter4/libraries/files.html


                $data = array(
                    'file_oldname' => $old_name,
                    'file_newname' => $new_name,
                    'file_post_id' => $_POST['posts_id'],
                    'file_ext'   => $ext,
                    'file_size'  => $size,
                    'file_ctime' => Date('Y-m-d H:i:s'),
                );

                $this->db->table('files')->insert($data);

              }
           }
        }




        // var_dump($file->isValid());

        //返回页面
        $url = base_url('main/post') . '/' . $_POST['posts_catagory'] . '/' . $_POST['posts_id'];
        $this->response->redirect($url);

        
    }





    public function post_filename_edit($post_catagory_id,$post_id,$file_id){
        $result = $this->db->table('files')->where('file_id', $file_id)->get()->getResultArray();
        $this->data['file'] = $result[0];

        $this->data['post_catagory_id'] = $post_catagory_id;

        $this->viewer('post_filename_edit');
    }




    public function post_filename_update(){
        $data = array(
            'file_oldname' => $_POST['file_rename'] . '.' . $_POST['file_ext'],
        );

        $this->db->table('files')->where('file_id', $_POST['file_id'])->update($data);

        //返回页面
        $url = base_url('main/post') . '/' . $_POST['post_catagory_id'] . '/' . $_POST['file_post_id'];
        $this->response->redirect($url);
    }






    public function file_get_array($database,$label,$file_post_id){
        $file_array = $this->db->table($database)->where($label, $file_post_id)->get()->getResultArray();
        return $file_array;
    }






















    // ==============================
    // Search
    // ==============================
    public function search(){
        $this->viewer('search');
    }


    public function search_result(){

        $this->data['keyword'] = $_POST['keyword'];

        $this->viewer('search_result');
    }































    // ==============================
    // Wiki
    // ==============================
    public function wiki(){
        $wiki_temp = $this->db->table('wiki')->orderBy('wiki_order', 'ASC')->get()->getResultArray();


        $new_posts_array = array();

        //对post进行具体化
        foreach ($wiki_temp as $wiki_post_key => $wiki_post_info) {
            $new_posts_array[$wiki_post_key] = $wiki_post_info;
            //post中的files具体化
            $new_posts_array[$wiki_post_key]["wiki_files_array"] = $this->file_get_array('wiki_files','file_wiki_id',$wiki_post_info["wiki_id"]);  
        }

        $this->data['wiki_array'] = $new_posts_array;

        $this->viewer('wiki');
    }



    public function wiki_add(){
        $data = array(
            'wiki_order' => '0',
            'wiki_title' => 'blank',
            'wiki_content' => 'blank blank',
            'wiki_ctime' => date('Y-m-d h:m:s'),
            'wki_utime' => time(),
        );

        $this->db->table('wiki')->insert($data);

        $url = base_url('main/wiki/');
        $this->response->redirect($url);
    }





    public function wiki_edit($id){
         $result= $this->db->table('wiki')->where('wiki_id', $id)->get()->getResultArray();
         $this->data['wiki'] = $result[0];

        $this->viewer('wiki_edit');
    }


    public function wiki_update(){


        $data = array(
            'wiki_title'   =>  $_POST["wiki_title"],
            'wiki_content'   =>  $_POST["wiki_content"],
            'wiki_order'   =>  $_POST["wiki_order"],
        );

        $this->db->table('wiki')->where('wiki_id', $_POST["wiki_id"])->update($data);





        //上传文件
        // var_dump($this->request->getFiles());
        if($files = $this->request->getFiles())
        {
           foreach($files['wiki_file'] as $file)
           {
              if ($file->isValid() && ! $file->hasMoved())
              {
                $newName = $file->getRandomName();
                $file->move('uploads_wiki/' . $_POST['wiki_id'], $newName);
                //就算没有这个文件夹，它都会自动创建文件夹

                $new_name = $file->getName();
                //1548171014_38866f66308887eee50f.jpg
                $old_name = $file->getClientName();
                //the_picture.jpg
                // $ext = $file->getClientExtension();
                $ext = substr(strrchr($new_name, '.'), 1);
                //jpg
                $size = $file->getSize('mb');
                //0.561
                //Working with Files
                //https://codeigniter4.github.io/CodeIgniter4/libraries/files.html


                $data = array(
                    'file_oldname' => $old_name,
                    'file_newname' => $new_name,
                    'file_wiki_id' => $_POST['wiki_id'],
                    'file_ext'   => $ext,
                    'file_size'  => $size,
                    'file_ctime' => Date('Y-m-d H:i:s'),
                );

                $this->db->table('wiki_files')->insert($data);

              }
           }
        }









        $url = base_url('main/wiki');
        $this->response->redirect($url);
    }

















    public function tool_catagory_title($catagory_id){
        $catagory_title_array = $this->db->table('catagory')->where('catagory_id', $catagory_id)->get()->getResultArray();
        return $catagory_title_array[0]["catagory_date"] . '-' . $catagory_title_array[0]["catagory_title"];
    }



    public function tool_tag_title($tag_string){

        // var_dump($tag_string);


        if($tag_string != ''){
            //将每个post中的tag拆开
            $tag_array = explode(',',$tag_string);

            //tag的信息替身
            $tag_new_array = array();
    
            //从数据库中取值
            foreach ($tag_array as $tag_key => $tag_id) {
                $tag_raw_array = $this->db->table('tag')->where('tag_id', $tag_id)->get()->getResultArray();
                $tag_new_array[$tag_key]['tag_id'] = $tag_id;
                $tag_new_array[$tag_key]['tag_title'] = $tag_raw_array[0]["tag_title"];
                // echo '<pre>';
                // var_dump($tag_new_array);
                // echo '</pre>';
            }

            // var_dump($tag_new_array);

            return $tag_new_array;
        }else{
            return 'none';
        }


    }




    public function tool_post_array_specific($posts_array){

        //新数组用来实现post数据具体化
        $new_posts_array = array();

        //对post进行具体化
        foreach ($posts_array as $post_key => $post_info) {

            $new_posts_array[$post_key] = $post_info;

            //post中的files具体化
            $new_posts_array[$post_key]["posts_files_array"] = $this->file_get_array('files','file_post_id',$post_info["posts_id"]);  

            //posts中的catagoryid具体化
            $new_posts_array[$post_key]["posts_catagory_title"] = $this->tool_catagory_title($post_info["posts_catagory"]);

            //posts中的tags_array具体化
            $new_posts_array[$post_key]["posts_tags_array"] = $this->tool_tag_title($post_info["posts_tag"]);
        }
        return $new_posts_array;
    }







    public function viewer($page){
		echo view('inc/header');
		echo view($page,$this->data);
		echo view('inc/footer');
    }



}
